package com.naizhuai.network;


import com.naizhuai.Model.db.user.PersonUserBean;
import com.naizhuai.ui.entity.management.CompanyBean;
import com.naizhuai.util.AppMD5Util;
import com.naizhuai.util.ConstantsPersonResources;
import com.naizhuai.util.NaizhuAILog;
import com.naizhuai.util.ConstantsParams;
import com.naizhuai.util.NetWorkUtils;
import com.naizhuai.util.PacageUtils;
import com.naizhuai.util.SharedPreferenceUtil;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;

import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * Created by code_han on 2018/1/29.
 */
// TODO: 2018/4/21 暂时不支持直接Body的方式 后面重构时再说吧
public class CommonParamsInterceptor implements Interceptor {

    private Context mContext;

    private String privateKey;

    private Gson mGson;

    public CommonParamsInterceptor(Context mContext, String privateKey) {
        this.mContext = mContext;
        mGson = new GsonBuilder().create();
        this.privateKey = privateKey;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {


        //获取到request
        Request request = chain.request();
        //获取到方法
        String method = request.method();
        ArrayList<String> paramsList = new ArrayList<>(Arrays.asList(ConstantsParams.PARAMS_KEYS));


        //公共参数hasmap

        try {

            //添加公共参数
            HashMap<String, Object> commomParamsMap = new HashMap<>();

            commomParamsMap.put(ConstantsParams.USER_ID_KEY, SharedPreferenceUtil.getInstance(mContext).getValue(PersonUserBean.USER_ID_KEY, ConstantsPersonResources.SP_DEFAULT_VALUE));
            commomParamsMap.put(ConstantsParams.SESSION_ID_KEY, SharedPreferenceUtil.getInstance(mContext).getValue(ConstantsPersonResources.SESSION_ID_KEY, ConstantsPersonResources.SESSION_ID_DEFAULT_VALUE));
            commomParamsMap.put(ConstantsParams.PLATFORM_KEY, ConstantsParams.PLATFORM_PHONE_ANDROID);
            commomParamsMap.put(ConstantsParams.APP_VERSION_KEY, PacageUtils.getVersionName(mContext));
            commomParamsMap.put(ConstantsParams.COMPANY_ID, SharedPreferenceUtil.getInstance(mContext).getValue(CompanyBean.COMPANY_ID_KEY, ""));

            commomParamsMap.put(ConstantsParams.NONCE_KEY, String.valueOf(System.currentTimeMillis()));

            commomParamsMap.put(ConstantsParams.APP_CHANNEL_KEY, PacageUtils.getAppMetaData(mContext, ConstantsPersonResources.APP_CHANNEL_NAME));
            commomParamsMap.put(ConstantsParams.CLIENT_SYSTEM_VERSION, PacageUtils.getSystemVersion());
            commomParamsMap.put(ConstantsParams.CLIENT_MAC_ADDRESS, PacageUtils.getMacAddress());
            commomParamsMap.put(ConstantsParams.CLIENT_MODEL, PacageUtils.getSystemModel());
            commomParamsMap.put(ConstantsParams.CLIENT_IDENTIFY, PacageUtils.getDeviceId(mContext));
            commomParamsMap.put(ConstantsParams.NETWORK_TYPE, NetWorkUtils.getNetworkState(mContext));
            commomParamsMap.put(ConstantsParams.CLIENT_PHONE_NUMBER, PacageUtils.getPhoneNumber(mContext));

            //get请求的封装
            if (method.equals("GET")) {
                //获取到请求地址api
                HttpUrl httpUrl = request.url();

//                LinkedHashMap<String, Object> rootMap = new LinkedHashMap<>();`
                //通过请求地址(最初始的请求地址)获取到参数列表
                Set<String> parameterNames = httpUrl.queryParameterNames();
                for (String key : parameterNames) {  //循环参数列表
                    paramsList.add(key);
                    commomParamsMap.put(key, httpUrl.queryParameter(key));
                }
                List<String> newList = new ArrayList(new TreeSet(paramsList));
//                Collections.sort(paramsList);
                StringBuilder sb = new StringBuilder();
                for (String strKey : newList) {
                    StringBuilder phone = new StringBuilder();
                    phone.append(commomParamsMap.get(strKey));
                    if (strKey.contains("phone")) {
                        int position = phone.indexOf(ConstantsParams.NONE_PARSE_CHAR);
                        if (position != -1)
                            phone.delete(position, position + 3);
                    }
                    sb.append(strKey).append("=").append(phone).append("&");
                }
                sb.deleteCharAt(sb.length() - 1);
                String newJsonParams = sb.toString();
                NaizhuAILog.e("---url_newJsonParams=" + newJsonParams);
                String sign;
                sign = newJsonParams + privateKey;
                NaizhuAILog.e("privateKey" + privateKey);
                sign = AppMD5Util.getMD5(AppMD5Util.getMD5(sign));
                String url = httpUrl.toString();
                int index = url.indexOf("?");
                if (index > 0) {
                    url = url.substring(0, index);
                }
                NaizhuAILog.e("---url_sign=" + sign);
                NaizhuAILog.e("privateKey=" + privateKey);
                url = url + "?" + ConstantsParams.SIGN + "=" + sign;  //拼接新的url
                url = url + "&" + newJsonParams;
                NaizhuAILog.e("url=" + url);
                request = request.newBuilder().url(url).build();  //重新构建请求

                //post请求的封装
            } else if (method.equals("POST")) {
                //重新拼接url+公共参数

                List<String> commonList = new ArrayList(new TreeSet(paramsList));
                StringBuilder commonStr = new StringBuilder();
                for (String strKey : commonList) {
                    StringBuilder phone = new StringBuilder();
                    phone.append(commomParamsMap.get(strKey));
                    if (strKey.contains("phone")) {
                        int position = phone.indexOf(ConstantsParams.NONE_PARSE_CHAR);
                        if (position != -1)
                            phone.delete(position, position + 3);
                    }
                    commonStr.append(strKey).append("=").append(phone).append("&");
                }
                commonStr.deleteCharAt(commonStr.length() - 1);
                String commonParams = commonStr.toString();

                HttpUrl httpUrl = request.url();
                String url = httpUrl.toString();
                int index = url.indexOf("?");
                if (index > 0) {
                    url = url.substring(0, index);
                }

                RequestBody requestBody = request.body();

                if (requestBody instanceof FormBody) {
                    //创建一个新的FromBoby
                    //获取原先的boby
                    FormBody body = (FormBody) request.body();
                    FormBody.Builder builder = new FormBody.Builder();
                    //遍历boby
                    for (int i = 0; i < body.size(); i++) {
                        String strKey = body.encodedName(i);
                        StringBuilder phone = new StringBuilder();
                        phone.append(body.encodedValue(i));
                        if (strKey.contains("phone")) {
                            int position = phone.indexOf(ConstantsParams.NONE_PARSE_CHAR);
                            if (position != -1)
                                phone.delete(position, position + 3);
                        }
                        paramsList.add(strKey);
                        commomParamsMap.put(strKey, URLDecoder.decode(phone.toString(), "utf-8"));
                        builder.add(strKey, URLDecoder.decode(phone.toString(), "utf-8"));

                        commomParamsMap.put(strKey, URLDecoder.decode(phone.toString(), "utf-8"));
                        builder.add(strKey, URLDecoder.decode(phone.toString(), "utf-8"));

                    }

                    List<String> newPostList = new ArrayList(new TreeSet(paramsList));
                    StringBuilder sb = new StringBuilder();
                    for (String strKey : newPostList) {
                        StringBuilder phone = new StringBuilder();
                        phone.append(commomParamsMap.get(strKey));
                        if (strKey.contains("phone")) {
                            int position = phone.indexOf(ConstantsParams.NONE_PARSE_CHAR);
                            if (position != -1)
                                phone.delete(position, position + 3);
                        }
                        sb.append(strKey).append("=").append(phone).append("&");
                    }
                    sb.deleteCharAt(sb.length() - 1);
                    String newJsonParams = sb.toString();

                    FormBody formBody = builder.build();
                    String newSign = newJsonParams + privateKey;
                    String strNewBodySign = AppMD5Util.getMD5(AppMD5Util.getMD5(newSign));
                    NaizhuAILog.e("newSign=" + newSign);
                    NaizhuAILog.e("strNewBodySign=" + strNewBodySign);

                    url = url + "?" + ConstantsParams.SIGN + "=" + strNewBodySign + "&" + commonParams;  //拼接新的url
                    NaizhuAILog.e("post url=" + url);
                    request = request.newBuilder().url(url).header("content-length", String.valueOf(formBody.contentLength())).post(formBody).build();
                } else if (requestBody instanceof MultipartBody) {

                    MultipartBody multiBody = (MultipartBody) requestBody;
                    List<MultipartBody.Part> parts = multiBody.parts();
                    for (MultipartBody.Part part : parts) {
                        Headers heads = (Headers) getFinalObject(part, "headers");
                        RequestBody body = (RequestBody) getFinalObject(part, "body");
                        if (body.contentType() != null && body.contentType().toString().contains("text")) {
                            String key = heads.get("Content-Disposition");
                            String[] splitKeys = key.split("=");
                            splitKeys[1] = splitKeys[1].replaceAll("\"", "");
                            Buffer buffer1 = new Buffer();
                            body.writeTo(buffer1);
                            String value = buffer1.readUtf8();
                            paramsList.add(splitKeys[1]);
                            commomParamsMap.put(splitKeys[1], value);

                        }
                    }

                    List<String> newPostList = new ArrayList(new TreeSet(paramsList));
                    StringBuilder sb = new StringBuilder();
                    for (String strKey : newPostList) {
                        StringBuilder phone = new StringBuilder();
                        phone.append(commomParamsMap.get(strKey));
                        if (strKey.contains("phone")) {
                            int position = phone.indexOf(ConstantsParams.NONE_PARSE_CHAR);
                            if (position != -1)
                                phone.delete(position, position + 3);
                        }
                        sb.append(strKey).append("=").append(phone).append("&");
                    }
                    sb.deleteCharAt(sb.length() - 1);
                    String newJsonParams = sb.toString();

                    String newSign = newJsonParams + privateKey;

                    String strNewBodySign = AppMD5Util.getMD5(AppMD5Util.getMD5(newSign));
                    NaizhuAILog.e("newSign=" + newSign);
                    NaizhuAILog.e("strNewBodySign=" + strNewBodySign);

                    url = url + "?" + ConstantsParams.SIGN + "=" + strNewBodySign + "&" + commonParams;  //拼接新的url

                    NaizhuAILog.e("post url=" + url);

                    request = request.newBuilder().url(url).post(requestBody).build();
                }
            }
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
        //最后通过chain.proceed(request)进行返回request对象
        return chain.proceed(request);
    }


    private Object getFinalObject(MultipartBody.Part part, String key) {
        Object value = null;
        try {
            Field field = part.getClass().getDeclaredField(key);
            field.setAccessible(true);
            value = field.get(part);
        } catch (Exception e) {
            NaizhuAILog.e("问题=" + e.getMessage());
        }
        return value;
    }


}
